// 导入数据库相关函数
import { initDB, saveDB, getAllQuestions, addQuestion, updateQuestion, deleteQuestion } from './db.js';

// 主应用
const { createApp } = Vue;

createApp({
    data() {
            return {
                currentView: 'quiz', // 默认显示刷题视图
                questions: [],
                shuffledQuestions: [],
                currentQuestionIndex: 0,
                currentQuestion: { question: '', type: 'single', options: [], correctAnswer: [] },
                userAnswer: [], // 数组，支持多选题
                showAnswer: false,
                answerMode: localStorage.getItem('answerMode') || 'immediate',
                
                // 模态框状态
                questionModalActive: false,
                editingQuestion: null,
                formQuestion: {
                    type: 'single', // single 或 multiple
                    question: '',
                    options: ['', '', '', '', ''], // 默认5个选项，支持动态增减
                    correctAnswer: [], // 数组，支持多选题
                    explanation: ''
                },
                
                // 通知
                notification: {
                    active: false,
                    message: '',
                    type: 'success' // success 或 error
                },
                
                // 错误信息
                errorMessage: '',
                
                // 分页相关
                currentPage: 1,
                pageSize: 50
            };
    },
    
    computed: {
        totalQuestions() {
            return this.questions.length;
        },
        
        // 当前页显示的题目
        paginatedQuestions() {
            const start = (this.currentPage - 1) * this.pageSize;
            const end = start + this.pageSize;
            return this.questions.slice(start, end);
        },
        
        // 总页数
        totalPages() {
            return Math.ceil(this.totalQuestions / this.pageSize);
        },
        
        // 页码数组
        pageNumbers() {
            const pages = [];
            for (let i = 1; i <= this.totalPages; i++) {
                pages.push(i);
            }
            return pages;
        }
    },

    watch: {
        answerMode(newValue) {
            localStorage.setItem('answerMode', newValue);
        }
    },
    
    async created() {
        try {
            // 初始化数据库连接
            await initDB();
            // 加载题目
            this.loadQuestions();
        } catch (error) {
            console.error('应用初始化失败:', error);
            this.errorMessage = error.message || '应用初始化失败，请刷新页面重试。';
        }
    },
    
    methods: {
        // 切换视图
        changeView(viewName) {
            try {
                this.currentView = viewName;
            } catch (error) {
                console.error('切换视图失败:', error);
                this.showNotification('切换视图失败: ' + error.message, 'error');
            }
        },
        
        // 加载所有题目
        async loadQuestions() {
            try {
                this.questions = await getAllQuestions();
                // 初始化页码
                this.currentPage = 1;
                // 初始化刷题
                this.initQuiz();
            } catch (error) {
                console.error('加载题目失败:', error);
                this.showNotification('加载题目失败: ' + error.message, 'error');
            }
        },
        
        // 切换到指定页码
        goToPage(page) {
            if (page >= 1 && page <= this.totalPages) {
                this.currentPage = page;
            }
        },
        
        // 上一页
        prevPage() {
            if (this.currentPage > 1) {
                this.currentPage--;
            }
        },
        
        // 下一页
        nextPage() {
            if (this.currentPage < this.totalPages) {
                this.currentPage++;
            }
        },
        
        // 处理选项数组，遇到空字符串则截断后面的选项
        processOptions(options) {
            const firstEmptyIndex = options.findIndex(option => option.trim() === '');
            if (firstEmptyIndex !== -1) {
                return options.slice(0, firstEmptyIndex);
            }
            return options;
        },
         
        // 初始化刷题
        initQuiz() {
            try {
                // 按做题次数升序排列，做题次数相同时随机排序
                this.shuffledQuestions = [...this.questions].sort((a, b) => {
                    const attemptCountA = a.attemptCount || 0;
                    const attemptCountB = b.attemptCount || 0;
                     
                    if (attemptCountA !== attemptCountB) {
                        return attemptCountA - attemptCountB;
                    } else {
                        // 做题次数相同时随机排序
                        return Math.random() - 0.5;
                    }
                });
                 
                this.currentQuestionIndex = 0;
                let question = this.shuffledQuestions[0] || {
                    question: '',
                    type: 'single',
                    options: [],
                    correctAnswer: []
                };
                
                // 处理选项，遇到空字符串则截断
                question.options = this.processOptions(question.options);
                
                this.currentQuestion = question;
                this.userAnswer = [];
                this.showAnswer = false;
            } catch (error) {
                console.error('初始化刷题失败:', error);
                this.showNotification('初始化刷题失败: ' + error.message, 'error');
            }
        },
        
        // 检查选项是否被选中
        isOptionSelected(index) {
            return this.userAnswer.includes(index);
        },
        
        // 检查选项是否为正确答案
        isCorrectAnswer(index) {
            // 只有在showAnswer为true时才返回正确答案信息
            if (!this.showAnswer) {
                return false;
            }
            return this.currentQuestion.correctAnswer.includes(index);
        },

        
        // 选择选项
        selectOption(index) {
            try {
                if (!this.showAnswer) {
                    // 单选题逻辑
                    if (this.currentQuestion.type === 'single') {
                        this.userAnswer = [index];
                    } 
                    // 多选题逻辑
                    else {
                        const indexInArray = this.userAnswer.indexOf(index);
                        if (indexInArray === -1) {
                            this.userAnswer.push(index);
                        } else {
                            this.userAnswer.splice(indexInArray, 1);
                        }
                    }
                    
                    // 如果是立即显示答案模式，单选题选择后自动提交，多选题需要明确提交
                    if (this.answerMode === 'immediate' && this.currentQuestion.type === 'single') {
                        this.handleSubmit();
                    }
                }
            } catch (error) {
                console.error('选择选项失败:', error);
                this.showNotification('选择选项失败: ' + error.message, 'error');
            }
        },


        
        // 检查是否可以提交
        canSubmit() {
            if (!this.currentQuestion) {
                return false;
            }
            if (this.currentQuestion.type === 'single') {
                return this.userAnswer.length === 1;
            } else {
                return this.userAnswer.length > 0;
            }
        },
        
        // 处理提交
        handleSubmit() {
            try {
                if (!this.canSubmit()) return;
                
                // 无论何种模式，提交后都显示答案
                this.showAnswer = true;
                
                // 增加做题次数
                this.incrementAttemptCount(this.currentQuestion.id);
                
                // 检查答案是否正确
                let isCorrect = true;
                
                // 检查所有正确答案是否都被选中
                this.currentQuestion.correctAnswer.forEach(answer => {
                    if (!this.userAnswer.includes(answer)) {
                        isCorrect = false;
                    }
                });
                
                // 检查是否有错误答案被选中
                this.userAnswer.forEach(answer => {
                    if (!this.currentQuestion.correctAnswer.includes(answer)) {
                        isCorrect = false;
                    }
                });
                
                // 如果答案不正确，增加错误次数
                if (!isCorrect) {
                    this.incrementWrongCount(this.currentQuestion.id);
                }
            } catch (error) {
                console.error('提交答案失败:', error);
                this.showNotification('提交答案失败: ' + error.message, 'error');
            }
        },



        
        // 下一题
        nextQuestion() {
            try {
                if (this.currentQuestionIndex < this.shuffledQuestions.length - 1) {
                    this.currentQuestionIndex++;
                    let question = this.shuffledQuestions[this.currentQuestionIndex];
                    // 处理选项，遇到空字符串则截断
                    question.options = this.processOptions(question.options);
                    this.currentQuestion = question;
                    this.userAnswer = [];
                    this.showAnswer = false;
                }
            } catch (error) {
                console.error('切换到下一题失败:', error);
                this.showNotification('切换到下一题失败: ' + error.message, 'error');
            }
        },
         
        // 上一题
        prevQuestion() {
            try {
                if (this.currentQuestionIndex > 0) {
                    this.currentQuestionIndex--;
                    let question = this.shuffledQuestions[this.currentQuestionIndex];
                    // 处理选项，遇到空字符串则截断
                    question.options = this.processOptions(question.options);
                    this.currentQuestion = question;
                    this.userAnswer = [];
                    this.showAnswer = false;
                }
            } catch (error) {
                console.error('切换到上一题失败:', error);
                this.showNotification('切换到上一题失败: ' + error.message, 'error');
            }
        },
        
        // 添加选项
        addOption() {
            try {
                this.formQuestion.options.push('');
            } catch (error) {
                console.error('添加选项失败:', error);
                this.showNotification('添加选项失败: ' + error.message, 'error');
            }
        },
        
        // 移除选项
        removeOption() {
            try {
                if (this.formQuestion.options.length > 2) { // 最少2个选项
                    // 如果移除的选项是正确答案，需要同步更新
                    const lastIndex = this.formQuestion.options.length - 1;
                    const answerIndex = this.formQuestion.correctAnswer.indexOf(lastIndex);
                    
                    if (answerIndex !== -1) {
                        this.formQuestion.correctAnswer.splice(answerIndex, 1);
                    }
                    
                    this.formQuestion.options.pop();
                }
            } catch (error) {
                console.error('移除选项失败:', error);
                this.showNotification('移除选项失败: ' + error.message, 'error');
            }
        },
        
        // 打开添加题目模态框
        openAddQuestionModal() {
            try {
                this.editingQuestion = null;
                this.formQuestion = {
                    type: 'single',
                    question: '',
                    options: ['', ''], // 默认2个选项
                    correctAnswer: [0], // 单选题默认选择第一个选项作为正确答案
                    explanation: ''
                };
                this.questionModalActive = true;
            } catch (error) {
                console.error('打开添加题目模态框失败:', error);
                this.showNotification('打开添加题目窗口失败: ' + error.message, 'error');
            }
          },
          
          // 打开编辑题目模态框
        openEditQuestionModal(question) {
            try {
                this.editingQuestion = question;
                this.formQuestion = {
                    type: question.type,
                    question: question.question,
                    options: [...question.options],
                    correctAnswer: [...question.correctAnswer],
                    explanation: question.explanation
                };
                this.questionModalActive = true;
            } catch (error) {
                console.error('打开编辑题目模态框失败:', error);
                this.showNotification('打开编辑题目窗口失败: ' + error.message, 'error');
            }
        },
        
        // 关闭题目模态框
        closeQuestionModal() {
            try {
                this.questionModalActive = false;
                // 重置表单和编辑状态
                this.editingQuestion = null;
                this.formQuestion = {
                    type: 'single',
                    question: '',
                    options: ['', ''],
                    correctAnswer: [],
                    explanation: ''
                };
            } catch (error) {
                console.error('关闭题目模态框失败:', error);
                this.showNotification('关闭题目窗口失败: ' + error.message, 'error');
            }
        },
        
        // 保存题目
        async saveQuestion() {
            try {
                // 验证表单
                if (!this.formQuestion.question.trim()) {
                    throw new Error('题目内容不能为空');
                }
                
                // 过滤空选项
                const validOptions = this.formQuestion.options.filter(option => option.trim() !== '');
                
                if (validOptions.length < 2) {
                    throw new Error('至少需要2个有效选项');
                }
                
                // 验证正确答案
                if (!this.formQuestion.correctAnswer || this.formQuestion.correctAnswer.length === 0) {
                    throw new Error('必须选择正确答案');
                }
                
                // 对于单选题，确保只有一个正确答案
                if (this.formQuestion.type === 'single' && this.formQuestion.correctAnswer.length > 1) {
                    throw new Error('单选题必须选择一个正确答案');
                }
                
                // 确保正确答案在有效选项范围内
                for (const index of this.formQuestion.correctAnswer) {
                    if (index < 0 || index >= validOptions.length) {
                        throw new Error('正确答案索引超出有效选项范围');
                    }
                }
                
                // 准备保存的数据
                const questionData = {
                    question: this.formQuestion.question,
                    options: validOptions,
                    correctAnswer: this.formQuestion.correctAnswer,
                    explanation: this.formQuestion.explanation,
                    type: this.formQuestion.type
                };
                
                if (this.editingQuestion) {
                    // 更新现有题目
                    await updateQuestion(this.editingQuestion.id, questionData);
                    this.showNotification('题目更新成功');
                } else {
                    // 添加新题目
                    await addQuestion(questionData);
                    this.showNotification('题目添加成功');
                }
                
                await saveDB();
                // 保存当前页码
                const currentPageNum = this.currentPage;
                // 重新加载题目
                await this.loadQuestions();
                // 恢复到之前的页码
                setTimeout(() => {
                    this.currentPage = currentPageNum;
                }, 0);
                this.closeQuestionModal();
            } catch (error) {
                console.error('保存题目失败:', error);
                this.showNotification('保存题目失败: ' + error.message, 'error');
            }
        },
        
        // 删除题目
        async handleDeleteQuestion(id) {
            try {
                console.log('handleDeleteQuestion被调用，题目ID:', id);
                console.log('this对象:', this);
                console.log('deleteQuestion函数:', deleteQuestion);
                
                if (confirm('确定要删除这个题目吗？')) {
                    console.log('用户确认删除');
                    const result = await deleteQuestion(id);
                    console.log('删除结果:', result);
                    await saveDB();
                    this.loadQuestions();
                    this.showNotification('题目删除成功');
                } else {
                    console.log('用户取消删除');
                }
            } catch (error) {
                console.error('删除题目失败:', error);
                this.showNotification('删除题目失败: ' + error.message, 'error');
            }
        },
        
        // 删除当前题目并跳转到下一题
        async deleteAndNextQuestion() {
            try {
                const currentQuestionId = this.currentQuestion.id;
                
                // 增加做题次数
                await this.incrementAttemptCount(currentQuestionId);
                
                // 标记题目为已删除
                await deleteQuestion(currentQuestionId);
                await saveDB();
                
                // 重新加载题目
                await this.loadQuestions();
                
                // 如果还有题目，跳转到下一题
                if (this.shuffledQuestions.length > 0) {
                    // 确保当前索引有效
                    if (this.currentQuestionIndex >= this.shuffledQuestions.length) {
                        this.currentQuestionIndex = this.shuffledQuestions.length - 1;
                    }
                    
                    let question = this.shuffledQuestions[this.currentQuestionIndex];
                    // 处理选项，遇到空字符串则截断
                    question.options = this.processOptions(question.options);
                    this.currentQuestion = question;
                    this.userAnswer = [];
                    this.showAnswer = false;
                }
                
                this.showNotification('题目已删除');
            } catch (error) {
                console.error('删除题目失败:', error);
                this.showNotification('删除题目失败: ' + error.message, 'error');
            }
        },
        
        // 增加错误次数
        async incrementWrongCount(questionId) {
            try {
                const question = this.questions.find(q => q.id === questionId);
                if (question) {
                    const newWrongCount = (question.wrongCount || 0) + 1;
                    // 更新题目
                    await updateQuestion(questionId, {
                        ...question,
                        wrongCount: newWrongCount
                    });
                    await saveDB();
                    // 更新本地数据
                    question.wrongCount = newWrongCount;
                }
            } catch (error) {
                console.error('增加错误次数失败:', error);
                // 这里不显示通知，避免影响用户体验
            }
        },
        
        // 增加做题次数
        async incrementAttemptCount(questionId) {
            try {
                const question = this.questions.find(q => q.id === questionId);
                if (question) {
                    const newAttemptCount = (question.attemptCount || 0) + 1;
                    // 更新题目
                    await updateQuestion(questionId, {
                        ...question,
                        attemptCount: newAttemptCount
                    });
                    await saveDB();
                    // 更新本地数据
                    question.attemptCount = newAttemptCount;
                }
            } catch (error) {
                console.error('增加做题次数失败:', error);
                // 这里不显示通知，避免影响用户体验
            }
        },
        
        // 清空所有错误次数
        async clearAllWrongCounts() {
            try {
                if (confirm('确定要清空所有题目的错误次数吗？')) {
                    // 遍历所有题目并更新错误次数
                    for (const question of this.questions) {
                        await updateQuestion(question.id, {
                            ...question,
                            wrongCount: 0
                        });
                    }
                    await saveDB();
                    this.loadQuestions();
                    this.showNotification('所有错误次数已清空');
                }
            } catch (error) {
                console.error('清空错误次数失败:', error);
                this.showNotification('清空错误次数失败: ' + error.message, 'error');
            }
        },
        
        // 清空所有数据
        async clearAllData() {
            try {
                if (confirm('确定要清空所有数据吗？此操作不可恢复！')) {
                    // 遍历所有题目并删除
                    for (const question of this.questions) {
                        await deleteQuestion(question.id);
                    }
                    await saveDB();
                    this.loadQuestions();
                    this.showNotification('所有数据已清空');
                }
            } catch (error) {
                console.error('清空数据失败:', error);
                this.showNotification('清空数据失败: ' + error.message, 'error');
            }
        },
        
        // 显示通知
        showNotification(message, type = 'success') {
            try {
                this.notification = {
                    active: true,
                    message: message,
                    type: type
                };
                
                // 3秒后自动隐藏通知
                setTimeout(() => {
                    this.notification.active = false;
                }, 3000);
            } catch (error) {
                console.error('显示通知失败:', error);
            }
        },

        // 获取总做题次数
        getTotalAttemptCount() {
            return this.questions.reduce((total, question) => {
                return total + (question.attemptCount || 0);
            }, 0);
        },
        
        // 触发文件上传
        triggerFileUpload() {
            try {
                document.getElementById('file-upload').click();
            } catch (error) {
                console.error('触发文件上传失败:', error);
                this.showNotification('触发文件上传失败: ' + error.message, 'error');
            }
        },
        
        // 处理文件上传
        async handleFileUpload(event) {
            try {
                const file = event.target.files[0];
                if (!file) return;
                
                const reader = new FileReader();
                reader.onload = async (e) => {
                    try {
                        await this.processFileContent(e.target.result, file.name);
                    } catch (error) {
                        console.error('处理文件内容失败:', error);
                        this.showNotification('处理文件失败: ' + error.message, 'error');
                    }
                };
                reader.onerror = () => {
                    this.showNotification('读取文件失败: ' + reader.error.message, 'error');
                };
                reader.readAsText(file);
                
                // 重置文件输入，以便可以重复上传同一文件
                event.target.value = '';
            } catch (error) {
                console.error('处理文件上传失败:', error);
                this.showNotification('文件上传失败: ' + error.message, 'error');
            }
        },
        
        // 处理文件内容
        async processFileContent(content, fileName) {
            try {
                let successCount = 0;
                let totalCount = 0;
                
                // 根据文件扩展名选择解析方式
                if (fileName.endsWith('.csv')) {
                    // 处理CSV格式
                    const lines = content.split(/\r?\n/).filter(line => line.trim() !== '');
                    totalCount = lines.length;
                    
                    // 使用for...of循环替代forEach，以便正确处理async/await
                    for (let index = 0; index < lines.length; index++) {
                        const line = lines[index];
                        try {
                            // 跳过表头行
                            if (index === 0 && line.toLowerCase().includes('题目')) {
                                continue;
                            }
                            
                            // 分割CSV行，处理可能包含逗号的字段
                            const parts = this.parseCsvLine(line);
                            
                            // 基本验证
                            if (parts.length < 5) { // 题目 + 至少2个选项 + 答案 + 解析
                                throw new Error(`格式不正确，字段不足`);
                            }
                            
                            // 解析字段
                            const question = parts[0].trim();
                            const optionsCount = parts.length - 3; // 总字段数 - 题目 - 答案 - 解析 - 题型
                            const options = [];
                            
                            for (let i = 1; i <= optionsCount; i++) {
                                if (i < parts.length - 2) { // 确保不越界
                                    options.push(parts[i].trim());
                                }
                            }
                            
                            // 解析正确答案
                            const correctAnswerStr = parts[parts.length - 3].trim();
                            const correctAnswers = correctAnswerStr.split(',').map(answer => {
                                // 将字母转换为索引（如A->0, B->1）
                                const index = answer.toUpperCase().charCodeAt(0) - 65;
                                if (index >= 0 && index < options.length) {
                                    return index;
                                }
                                throw new Error(`正确答案${answer}无效`);
                            });
                            
                            // 解析解析
                            const explanation = parts[parts.length - 2]?.trim() || '';
                            
                            // 解析题型
                            let type = 'single';
                            if (parts.length >= 9 && parts[parts.length - 1]) {
                                type = parts[parts.length - 1].toLowerCase().includes('multiple') ? 'multiple' : 'single';
                            }
                            
                            // 使用API添加题目
                            const questionData = {
                                question: question,
                                options: options,
                                correctAnswer: correctAnswers,
                                explanation: explanation,
                                type: type
                            };
                            await addQuestion(questionData);
                            
                            successCount++;
                        } catch (error) {
                            console.error(`处理第${index + 1}题时出错:`, error.message);
                        }
                    }
                } else if (fileName.endsWith('.txt')) {
                    // 处理TXT格式（简单格式，假设每行一个题目）
                    const lines = content.split(/\r?\n/).filter(line => line.trim() !== '');
                    let i = 0;
                    
                    while (i < lines.length) {
                        try {
                            // 尝试解析一组题目（题目+选项+答案+解析）
                            const questionBlock = [];
                            let j = i;
                            
                            // 收集题目块（直到遇到下一个题目编号或文件结束）
                            while (j < lines.length && !lines[j].match(/^\d+、/)) {
                                questionBlock.push(lines[j]);
                                j++;
                            }
                            
                            // 如果没有收集到任何行，跳过
                            if (questionBlock.length === 0) {
                                i++;
                                continue;
                            }
                            
                            // 解析题目块
                            await this.parseQuestionBlock(questionBlock);
                            successCount++;
                            i = j;
                        } catch (error) {
                            console.error(`处理第${i + 1}行时出错:`, error.message);
                            i++;
                        }
                    }
                    
                    totalCount = lines.length;
                }
                
                await saveDB();
                this.loadQuestions();
                this.showNotification(`导入完成，成功导入 ${successCount} 道题，共 ${totalCount} 道题`);
            } catch (error) {
                console.error('处理文件内容失败:', error);
                this.showNotification('处理文件失败: ' + error.message, 'error');
            }
        },
        
        // 解析题目块（TXT格式）
        async parseQuestionBlock(block) {
            try {
                // 解析题目行（第一行）
                let firstLine = block[0];
                // 移除题目编号（如"3、"）
                firstLine = firstLine.replace(/^\d+、/, '').trim();
                
                // 提取题型（如"[多选]"）
                let type = 'single';
                let questionText = firstLine;
                if (firstLine.includes('[')) {
                    const typeMatch = firstLine.match(/\[(.+?)\]/);
                    if (typeMatch && typeMatch[1].includes('多')) {
                        type = 'multiple';
                    }
                    // 移除题型标记
                    questionText = firstLine.replace(/\s*\[[^\]]+\]\s*/, '').trim();
                }
                
                // 提取选项（寻找以"- 字母："开头的行）
                const options = [];
                let optionLineIndex = 1;
                while (optionLineIndex < block.length) {
                    const line = block[optionLineIndex];
                    if (line.match(/^[A-Za-z]\.?\s*[:：]/) || line.match(/^-\s*[A-Za-z]\s*[:：]/)) {
                        // 提取选项内容（移除选项标识如A.或A：或-A：）
                        const optionContent = line.replace(/^(-\s*)?([A-Za-z]\.?\s*[:：]\s*)/, '').trim();
                        options.push(optionContent);
                        optionLineIndex++;
                    } else {
                        break;
                    }
                }
                
                if (options.length < 2) {
                    throw new Error('至少需要2个有效选项');
                }
                
                // 解析正确答案（寻找包含"答案"的行）
                const correctAnswer = [];
                while (optionLineIndex < block.length) {
                    const line = block[optionLineIndex].toLowerCase();
                    if (line.includes('答案')) {
                        // 提取答案字母
                        const answersMatch = line.match(/答案[:：]?\s*([A-Za-z,]+)/);
                        if (answersMatch) {
                            const answerLetters = answersMatch[1].split(/[\s,，]+/).filter(Boolean);
                            answerLetters.forEach(letter => {
                                const index = letter.toUpperCase().charCodeAt(0) - 65;
                                if (index >= 0 && index < options.length) {
                                    correctAnswer.push(index);
                                }
                            });
                        }
                        break;
                    }
                    optionLineIndex++;
                }
                
                if (correctAnswer.length === 0) {
                    throw new Error('未找到正确答案');
                }
                
                // 解析解析部分
                let explanation = '';
                const explanationLineIndex = optionLineIndex + 1;
                if (explanationLineIndex < block.length && block[explanationLineIndex].includes('解析：')) {
                    explanation = block[explanationLineIndex].replace('解析：', '').trim();
                }
                
                // 使用API添加题目
                const questionData = {
                    question: questionText,
                    options: options,
                    correctAnswer: correctAnswer,
                    explanation: explanation,
                    type: type
                };
                await addQuestion(questionData);
            } catch (error) {
                console.error('解析题目块失败:', error);
                throw error;
            }
        },
        
        // 解析CSV行，处理包含逗号的字段
        parseCsvLine(line) {
            const parts = [];
            let currentPart = '';
            let inQuotes = false;
            let quoteCount = 0;
            
            for (let i = 0; i < line.length; i++) {
                const char = line[i];
                
                if (char === '"') {
                    quoteCount++;
                    // 检查是否是双引号（转义的引号）
                    if (i < line.length - 1 && line[i + 1] === '"') {
                        currentPart += '"';
                        i++; // 跳过下一个引号
                        quoteCount = 0;
                    } else {
                        inQuotes = !inQuotes;
                    }
                } else if (char === ',' && !inQuotes) {
                    parts.push(currentPart);
                    currentPart = '';
                } else {
                    currentPart += char;
                }
            }
            
            // 添加最后一个部分
            parts.push(currentPart);
            
            // 处理可能未闭合的引号
            if (quoteCount % 2 !== 0) {
                console.warn('CSV行可能包含未闭合的引号:', line);
            }
            
            return parts;
        },
        
        // 下载导入模板
        downloadTemplate() {
            try {
                const templateContent = `题目,选项A,选项B,选项C,选项D,选项E,正确答案(字母，如A,B),解析,题型(single/multiple)
1+1等于几?,0,1,2,3,,A,1+1=2是基本的数学加法,single
Vue.js是什么?,一种水果,JavaScript框架,游戏,操作系统,,B,Vue.js是一套用于构建用户界面的渐进式JavaScript框架,single
以下哪些是前端框架?,Vue.js,React,Java,Angular,,A,B,D,Java是后端语言,multiple`;
                
                const blob = new Blob([templateContent], { type: 'text/csv;charset=utf-8;' });
                const url = URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.setAttribute('href', url);
                link.setAttribute('download', '题目导入模板.csv');
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            } catch (error) {
                console.error('下载模板失败:', error);
                this.showNotification('下载模板失败: ' + error.message, 'error');
            }
        },
        
        // 导出所有题目
        exportQuestions() {
            try {
                this.exportToCSV(this.questions, '所有题目');
            } catch (error) {
                console.error('导出所有题目失败:', error);
                this.showNotification('导出题目失败: ' + error.message, 'error');
            }
        },
        
        // 导出错题
        exportWrongQuestions() {
            try {
                const wrongQuestions = this.questions.filter(q => q.wrongCount > 0);
                this.exportToCSV(wrongQuestions, '错题集');
            } catch (error) {
                console.error('导出错题失败:', error);
                this.showNotification('导出错题失败: ' + error.message, 'error');
            }
        },
        
        // 导出到CSV
        exportToCSV(questions, fileName) {
            try {
                if (questions.length === 0) {
                    this.showNotification('没有可导出的题目', 'error');
                    return;
                }
                
                // 构建CSV表头
                let csvContent = "题目";
                // 最多支持6个选项
                for (let i = 0; i < 6; i++) {
                    csvContent += `,选项${String.fromCharCode(65 + i)}`;
                }
                csvContent += ",正确答案(字母),解析,题型,错误次数\n";
                
                questions.forEach(question => {
                    // 处理正确答案格式（转换为字母）
                    const correctAnswerLetters = question.correctAnswer.map(index => 
                        String.fromCharCode(65 + index)
                    ).join(',');
                    
                    const row = [question.question];
                    
                    // 添加选项
                    question.options.forEach(option => {
                        row.push(option);
                    });
                    
                    // 填充空白选项
                    for (let i = question.options.length; i < 6; i++) {
                        row.push('');
                    }
                    
                    // 添加其他字段
                    row.push(
                        correctAnswerLetters,
                        question.explanation || '',
                        question.type,
                        question.wrongCount || 0
                    );
                    
                    // 处理包含逗号的字段
                    const escapedRow = row.map(field => {
                        // 确保field是字符串类型
                        const fieldStr = String(field);
                        if (fieldStr.includes(',') || fieldStr.includes('"') || fieldStr.includes('\n')) {
                            return `"${fieldStr.replace(/"/g, '""')}"`;
                        }
                        return fieldStr;
                    });
                    
                    csvContent += escapedRow.join(',') + "\n";
                });
                
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                const url = URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.setAttribute('href', url);
                link.setAttribute('download', `${fileName}_${new Date().toLocaleDateString()}.csv`);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                this.showNotification(`成功导出 ${questions.length} 道题`);
            } catch (error) {
                console.error('导出到CSV失败:', error);
                this.showNotification('导出失败: ' + error.message, 'error');
            }
        },
        
        // 获取错题数量
        getWrongQuestionsCount() {
            return this.questions.filter(q => q.wrongCount > 0).length;
        },
        
        // 获取所有题目的总错误次数
        getTotalWrongCount() {
            return this.questions.reduce((total, q) => total + (q.wrongCount || 0), 0);
        },
        
        // 获取易错题数量（错误次数≥3次）
        getHardQuestionsCount() {
            return this.questions.filter(q => (q.wrongCount || 0) >= 3).length;
        }
    }
}).mount('#app');